package com.company;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 查找器
 */
public class Finder {

    private static Color[] checkArr;

    static {
        checkArr = new Color[]{
                new Color(138, 148, 158),
                new Color(98, 88, 69),
                new Color(149, 129, 99),
                new Color(229, 169, 119),
                new Color(199, 137, 95),
                new Color(144, 100, 73),
                new Color(174, 126, 90),
                new Color(170, 123, 89),
                new Color(172, 124, 91),
                new Color(172, 122, 88),
                new Color(136, 89, 65)};
    }

    /**
     * 查找程序窗口的左上角点的坐标 锚点
     */
    public Point findAnchor() {
        System.out.println("finding the anchor.");
        Point anchor = null;

        //屏幕大小
        Dimension dimension = screenSize();
        int width = (int) dimension.getWidth();
        int height = (int) dimension.getHeight();

        //截屏
        BufferedImage bufferedImage = RB.createScreenCapture(new Rectangle(width, height));

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (check(bufferedImage, x, y)) {
                    System.out.println("找到检查点：");
                    System.out.println("x:" + x + " y:" + y);
                    anchor = new Point(x - 7, y - 9);
                    System.out.println("锚点：" + anchor);
                    return anchor;
                }
            }
        }

        System.out.println("未能获取锚点.");
        return null;
    }

    private boolean check(BufferedImage image, int x, int y) {
        for (int i = 0; i < checkArr.length; i++) {
            if (image.getRGB(x + i, y) == checkArr[i].getRGB()) {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }

    private Dimension screenSize() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        return screenSize;
    }

}
